package com.manage.service;

import com.manage.ManageConstants;
import com.manage.mapper.UserSmsMapper;
import com.manage.pojo.UserSms;
import com.manage.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;

import static com.manage.result.CodeMsg.*;

@Service
public class UserSmsService {

    @Autowired
    UserSmsMapper mUserSmsMapper;

    public Result<UserSms> sendSMS(String mobilePhone, long smsType) {

        UserSms userSms = new UserSms();
        try {
            List<UserSms> userSmsList = querySmsByMobilePhone(mobilePhone);
            if (userSmsList == null) {
                return Result.error(SMS_IS_ERROR);
            }
            //删除24小时之前的信息数据
            Date nowDate = new Date();
            for (UserSms item : userSmsList) {
                if ((item.getSendTime().getDay() != nowDate.getDay())) { //todo：这种删除会把两天交接的时间点需要用的短息数据删除，进而产生BUG
                    mUserSmsMapper.delete(item);
                }
            }

            //产生短信验证码4位随机数
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            userSms.setMobilePhone(mobilePhone);
            userSms.setSmsType(smsType);
            String ranStr = random.nextInt() + "00000";
            userSms.setSmsCode(ranStr.substring(1, 5));
            userSms.setSendTime(new Date());
            userSms.setUsedState(0L);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return Result.error(Send_SMS_QUERY_ERROR);
            //todo：如果有问题包发送短信异常，后面增加时间判断放防止同一个手机一分钟之内多次请求发短信
        }

        if (ManageConstants.OPERATE_SUCCESSFULLY == mUserSmsMapper.insert(userSms)) {
            return Result.success(userSms);
        } else {
            return Result.error(Send_SMS_INSERT_ERROR);
        }
    }

    List<UserSms> querySmsByMobilePhone(String mobilePhone) {
        Example userSmsExample = new Example(UserSms.class);
        Example.Criteria userSmsCriteria = userSmsExample.createCriteria();
        userSmsCriteria.andEqualTo("mobilePhone", mobilePhone);
        try {
            return mUserSmsMapper.selectByExample(userSmsExample);
        } catch (Exception e) {
            return null;
        }
    }

    int updateSms(UserSms userSms) {
        return mUserSmsMapper.updateByPrimaryKey(userSms);
    }
}
